<?php


namespace App\Services\Admin;


use App\Http\Controllers\Api\RemoteApiRoute;
use App\Models\Asin;
use App\Models\Category;
use App\Models\Task;
use Illuminate\Support\Facades\Http;

class CategoryService
{
    public function __construct()
    {

    }

    /**
     * 获取所有一级分类
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getCategoryInfo($params){
        if (!isset($params['domainId'])){
            $params['domainId'] = 3; //默认获取德国
        }
        $categories = Category::where($params)->get();

        //本地无分类请求服务器
        if (!count($categories)){
            $url = env('REMOTE_API_URL') . RemoteApiRoute::CATEGORY_INFO;
            $response = Http::post($url,$params);
            if ($response->ok()){
                Category::insert($response->json()['result']);
                $categories = Category::where($params)->get();
            }else{
                return Error($response->reason());
            }
        }
        $categories = $this->init_categories($categories, 0);

        // 使用usort和自定义比较函数进行排序
        usort($categories, function($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });

        return Success('ok', $categories);
    }

    /**
     * 获取子分类
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getChildrenInfo($params){
        $category = Category::where($params)->first();
        if ($category->childrens){
            $children = explode(',',$category->childrens);
            $categories = Category::whereIn('catId',$children)->get();

            //本地无分类请求服务器
            if (!count($categories)){
                $url = env('REMOTE_API_URL') . RemoteApiRoute::CATEGORY_INFO;
                $post = ['domainId' => $params['domainId'], 'catId' => $category->childrens];
                $response = Http::post($url,$post);
                if ($response->ok()){
                    Category::insert($response->json()['result']);
                    return $response->json();
                }else{
                    return Error($response->reason());
                }
            }
        }else{
            return Error('该分类下无子分类！');
        }
        return Success('ok', $categories);
    }

    public function getCategoryProduct($params){
        if (!isset($params['numbers'])){
            return Error('请输入获取数量！');
        }
        if ($params['numbers'] < 50){
            return Error('最小数量为50！');
        }

        //最近三天内更新数据
        $where = ['domainId' => $params['domainId'], 'catId' => $params['catId']];
        if (isset($params['recent_update']) && $params['recent_update']){
            $recent_update = (int)$params['recent_update'];
            $time_gte = strtotime("-3 days");
            $time_lte = time();
            $where['create_time'] = ['$gte' => $time_gte, '$lte' => $time_lte];
        }else{
            $recent_update = 0;
        }
        $where['sort_key'] = ['$gte' => $params['sales_rank_low'], '$lte' => $params['sales_rank_high']];
        $asins = Asin::where($where)->get();

        //若数量不足则重新获取
        if (count($asins) < $params['numbers']){
            $url = env('REMOTE_API_URL') . RemoteApiRoute::CATEGORY_PRODUCT;
            $response = Http::post($url,$params);
            if ($response->ok()){
                $re = $response->json();
                if ($re['code'] == 0){

                    //自动生成任务记录
                    $task_record = [
                        'cat_id' => $params['catId'],
                        'cat_name' => $params['catName'],
                        'domain_id' => $params['domainId'],
                        'sales_rank_range' => $params['sales_rank_low'].'~'.$params['sales_rank_high'],
                        'counts' => $params['numbers'],
                        'recent_update' => $recent_update,
                        'get_product_status' => 'wait',
                        'create_time' => time()
                    ];
                    $record = Task::create($task_record);

                    //插入前删除旧数据
                    Asin::where(['domainId' => (int)$params['domainId'], 'catId' => (int)$params['catId'], 'sort_key' => ['$gte' => $params['sales_rank_low'], '$lte' => $params['sales_rank_high']]])->delete();
                    Asin::insert($re['result']);

                    return Success($re['message'], $record);
                }else{
                    return Error($re['message']);
                }
            }else{
                return Error($response->reason());
            }
        }
        return Success('该条件下本地已有获取记录，请勿重复操作！', $asins);
    }

    /**
     * 递归解析菜单结构
     * @param $menu
     * @return array
     */
    private function init_categories($data, $pId)
    {
        $tree = array();
        foreach ($data as $k => $v) {

            if ($v->parent == $pId) {
                $children = $this->init_categories($data, $v->catId);
                if ($children){
                    $v->children = $children;
                }

                //排序
                $sort[] = $v->catId;
                $tree[] = $v;
                array_multisort($sort,SORT_NUMERIC,SORT_ASC,$tree);
                unset($data[$k]);
            }
        }
        return $tree;
    }


}
